//
//  DetailViewController.m
//  test
//
//  Created by Jeoffrey Thirot on 12/03/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GameViewController.h"

@implementation GameViewController
@synthesize TreasureBtn1 = _TreasureBtn1;
@synthesize TreasureBtn2 = _TreasureBtn2;
@synthesize TreasureBtn3 = _TreasureBtn3;
@synthesize TreasureBtn4 = _TreasureBtn4;

@synthesize gameDatas = _gameDatas;
@synthesize detailDescriptionLabel = _detailDescriptionLabel;
@synthesize mapView = _mapView;
@synthesize treasureMenuView = _treasureMenuView;
@synthesize menuState;

@synthesize playerName, challengerName, numPlayer;
@synthesize gameOverView = _gameOverView;


@synthesize delegateBTSession = _delegateBTSession;

- (void)dealloc
{
    [_gameDatas release];
    [_detailDescriptionLabel release];
    [_mapView release];
    [_treasureMenuView release];
    [_TreasureBtn1 release];
    [_TreasureBtn2 release];
    [_TreasureBtn3 release];
    [_TreasureBtn4 release];
    [_gameOverView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_mapView initForController];
    [self setDatas];
    menuState = TREASURE_PLACEMENT;
}

- (void)setDatas
{
    _gameDatas = [[GameDataController alloc] init];
    
    int squareW = 40;
    int squareH = 40;
    int mapW = _mapView.bounds.size.width;
    int mapH = _mapView.bounds.size.height;
    
    int numSquaresX = mapW / squareW;
    int numSquaresY = mapH / squareH;
    
    int squareId = 1;
    
    for (int i = 0; i < numSquaresY; i++) 
    {
        for (int j = 0; j < numSquaresX; j++)
        {
            int squareXa = squareW * j;
            int squareYa = squareH * i;
            int squareXb = squareXa + squareW;
            int squareYb = squareYa + squareH;
            CGPoint coordsA = {squareXa, squareYa};
            CGPoint coordsB = {squareXb, squareYb};
            [_gameDatas addMapDataWithName:squareId andCoordsA:coordsA andCoordsB:coordsB];
            [_mapView addSquareOnMapWithId:[NSNumber numberWithInt:squareId] andCoords:coordsA];
            squareId++;
        }
    }
    
    [_gameDatas addTreasureMenuDataWithName:0];
    [_gameDatas addTreasureMenuDataWithName:1];
    [_gameDatas addTreasureMenuDataWithName:2];
    [_gameDatas addTreasureMenuDataWithName:3];
    
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    [self setTreasureBtn1:nil];
    [self setTreasureBtn2:nil];
    [self setTreasureBtn3:nil];
    [self setTreasureBtn4:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    //return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


#pragma mark - Init Methods

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"init GameViewController");
    }
    return self;

}

- (IBAction)backAction:(id)sender {
    [self returnHome];
}

- (void) returnHome
{
    NSLog(@"returnHome...");
    [self.delegateBTSession clearSession];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Touch Methods
							
- (IBAction)onTreasureMenuBtnTouched:(id)sender 
{
    NSNumber *index = [NSNumber numberWithInteger:[sender tag]];
    [self treasureButtonTouchedById:index];
    
    NSDictionary *info = [NSDictionary dictionaryWithObject:index forKey:@"Touch"];
    [self.delegateBTSession sendData:info];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    UIView *touchedView = touch.view;
    if (touchedView == self.mapView) 
    {
        CGPoint touchLocation = [touch locationInView:touchedView];
        NSMutableDictionary *dict = [_gameDatas compareDataWithCoords:touchLocation];
        float squareHit = [[dict objectForKey:@"name"] floatValue];
        if (squareHit != 0)
        {
            if (menuState == TREASURE_PLACEMENT)
                [self mapAction:2 bySquareId:squareHit withDict:dict];
            else if (menuState == TREASURE_SEARCH)
                [self mapAction:1 bySquareId:squareHit withDict:dict];
        }
        else
            NSLog(@"MapView > touchesEnded > square not found");
    }
}

- (void)treasureButtonTouchedById:(NSNumber *)index
{
    if ([self.gameDatas getTreasureButtonTouchableById:index] == YES)
    {
        [self.gameDatas setCurrentTreasureButton:index];
        [self.gameDatas setTreasureButton:index selected:YES];
    }
    else NSLog(@"on ne place pas deux fois le même trésor");
}

- (void)mapAction:(int)action bySquareId:(float)squareId withDict:(NSMutableDictionary *)dict
{
    switch (action) 
    {
        case 0: // walk
            //
            break;
        case 1: // dig
            [self searchChallengerTreasureBySquareId:squareId andDict:dict];
            break;
        case 2: // bury
            [self buryTreasureOnSquareId:squareId andDict:dict];
            break;
        default:
            break;
    }
}

- (void)buryTreasureOnSquareId:(float)squareId andDict:(NSMutableDictionary *)dict
{
    NSNumber *currentTreasure = [self.gameDatas getCurrentTreasureButton];
    if (currentTreasure != Nil)
    {
        BOOL isOccupied = [self.gameDatas isSquareOccupiedBySquareId:[NSNumber numberWithFloat:squareId]];
        if (isOccupied == NO)
        {
            NSLog(@"on place le trésor %@ en case %f ", currentTreasure, squareId);
            [self.mapView addTreasureOnMapWithId:[NSNumber numberWithFloat:squareId]];
            [self.gameDatas setCurrentTreasureButton:Nil];
            [self.gameDatas setTreasureButton:currentTreasure clickable:NO];
            [self.gameDatas setTreasureButton:currentTreasure selected:NO];
            [self.gameDatas addTreasureOnMapBySquareId:[NSNumber numberWithFloat:squareId]];
            if ([self.gameDatas isTreasureMenuTouchable] == NO) [self hideTreasureMenu];
        }
        else NSLog(@"on ne peut pas placer un trésor deux fois sur la même case");
    }
}

- (void)searchChallengerTreasureBySquareId:(float)squareId andDict:(NSMutableDictionary *)dict
{
    BOOL isVisited = [self.gameDatas isSquareVisitedBySquareId:[NSNumber numberWithFloat:squareId]];
    if (isVisited == NO)
    {
        NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"flag", [NSNumber numberWithFloat:squareId], @"squareId", nil];
        [self.delegateBTSession sendData:data];
    }
}

- (void)hideTreasureMenu
{
    menuState = TREASURE_SEARCH;
    
    CGPoint oldLocation = {_treasureMenuView.frame.origin.x + (_treasureMenuView.frame.size.width / 2),
                            _treasureMenuView.frame.origin.y + (_treasureMenuView.frame.size.height / 2)};
    CGPoint newLocation = {_treasureMenuView.frame.origin.x + (_treasureMenuView.frame.size.width / 2), 
                           [UIScreen mainScreen].bounds.size.height + (_treasureMenuView.frame.size.height / 2)};
    CAKeyframeAnimation *move = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef movePath = CGPathCreateMutable();
    CGPathMoveToPoint(movePath, nil, oldLocation.x, oldLocation.y);
    CGPathAddLineToPoint(movePath, nil, oldLocation.x, oldLocation.y - 20);
    CGPathAddLineToPoint(movePath, nil, newLocation.x, newLocation.y);
    [_treasureMenuView setCenter:newLocation];
    [move setPath:movePath];
    CGPathRelease(movePath);
    
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    [animationGroup setDuration:0.6];
    [animationGroup setAnimations:[NSArray arrayWithObjects:move, nil]];
    CALayer *viewLayer = _treasureMenuView.layer;
    [viewLayer addAnimation:animationGroup forKey:@"animations"];
}

#pragma mark - Method exchange data

- (void) receiveData:(NSNotification *)notification
{
    NSLog(@"receive data : %@", [notification userInfo]);
    NSDictionary *info = [notification userInfo];
    NSNumber *squareId;
    BOOL isTreasure;
    NSDictionary *data;
    
    switch ([[info objectForKey:@"flag"] intValue]) {
        case 1:
            squareId = [info objectForKey:@"squareId"];
            isTreasure = [self receiveIsTreasureBySquareId:squareId];
            NSLog(@" case 1 squareId : %@, isTreasure : %d", squareId, isTreasure);
            data = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"flag", [NSNumber numberWithBool:isTreasure], @"isTreasure", squareId, @"squareId", nil];
            [self.delegateBTSession sendData:data];
            break;
        case 2 :
            isTreasure = [[info objectForKey:@"isTreasure"] boolValue];
            squareId = [info objectForKey:@"squareId"];
            NSLog(@" case 2 squareId : %@, isTreasure : %d", squareId, isTreasure);
            [self isTreasureDiscovered:isTreasure andSquareId:squareId];
            break;
        case 3 :
            NSLog(@"case 3");
            menuState = GAME_OVER;
            [self showGameOverScreen:NO];
            break;
        default:
            break;
    }
}

- (void) disconnect:(NSNotification *)notification
{
    NSLog(@"disconnect data : %@", [notification userInfo]);
    [self returnHome];
}

- (void) setDelegateBTSession:(BTSession *)delegateBTSession
{
    [delegateBTSession retain];
    [_delegateBTSession release];
    _delegateBTSession = delegateBTSession;
    NSLog(@"setDelegateBTSession %@", self.delegateBTSession);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveData:) name:kSBReceiveDataFromSession object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disconnect:) name:kSBDisconnectedSession object:nil];
}

- (void) namePlayer:(NSString *)namePlayer andNumPlayer:(int)playerNum andChallengerName:(NSString *)nameChallenger
{
    self.playerName = [namePlayer retain];
    self.challengerName = [nameChallenger retain];
    self.numPlayer = playerNum;
}

- (BOOL) receiveIsTreasureBySquareId:(NSNumber *)squareId
{
    BOOL isTreasure = [self.gameDatas isTreasureOnSquareBySquareId:squareId];
    return isTreasure;
}

- (void)isTreasureDiscovered:(BOOL)isTreasure andSquareId:(NSNumber *)squareId
{
    NSLog(@"isTreasureDiscovered %d andSquareId %@", isTreasure, squareId);
    if (isTreasure == YES)
    {
        NSLog(@"if is treasure");
        [self.gameDatas setTreasureDiscoveredBySquareId:squareId];
        [self.mapView addFoundTreasureOnMapWithId:squareId];
    }
    else
    {
        [self.gameDatas setSquareDugBySquareId:squareId];
        [self.mapView addHoleOnMapWithId:squareId]; 
    }
    BOOL allTreasureDiscovered = [self.gameDatas getAllTreasureDiscovered];
    if (allTreasureDiscovered == YES) 
    {
         NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:3], @"flag", nil];
        [self.delegateBTSession sendData:data];
        [self showGameOverScreen:YES];
    }
}

- (void)showGameOverScreen:(BOOL)isWon
{
    NSString *label;
    if(isWon == YES)
    {
        label = [NSString stringWithFormat:@"Bravo %@ tu as gagné", self.playerName];
    }
    else
    {
        label = [NSString stringWithFormat:@"Dommage %@, tu as perdu. %@ a été plus fort que toi", self.playerName, self.challengerName];
    }
    if( _gameOverView != nil ) {
        [_gameOverView release];
    }
    _gameOverView = [[GameOverView alloc] initWithFrame:CGRectMake(20, 170, 200, 150) andLabel:label];
    [self.view addSubview:self.gameOverView];
    
}

@end
